package com.easyselection.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.easyselection.dto.UserDTO;
import com.easyselection.utils.JwtUtils;
import com.easyselection.utils.RedisConstants;
import com.easyselection.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 90616
 * @description JWT校验拦截器
 * @create 2025/7/5 0:24
 */
@Slf4j
public class JsonWebTokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public JsonWebTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取到请求路径
        String requestURI = request.getRequestURI();

//        //2. 判断路径是否包含/login，若是表示登录操作，直接放行
//        if(requestURI.contains("/login")){
//            log.info("登录请求, 放行!");
//            return true;
//        }
        //3. 获取请求中的token
        String token = request.getHeader("authorization");

        //4. 判断token是否存在 如果不存在表示用户未登录, 返回401错误
        if(token == null || token.isEmpty()){
            response.setStatus(401);
            return false;
        }

        //5.如果token存在, 对令牌进行校验
        //存储user到threadLocal当中
        try {
            JwtUtils.parseJWT(token);
            String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
            if(stringRedisTemplate.opsForHash().entries(tokenKey).isEmpty()){
                //身份过期
                response.setStatus(401);
                return false;
            }

            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
            //6. 将查询到的hash数据转换为UserDTO对象
            UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
            //7. 存在,保存用户信息到threadLocal
            UserHolder.saveUser(userDTO);
            //8. 刷新token有效期
            stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌非法, 返回401错误");
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
